"""
---------------------------------------------------------------------
- File: router.py
- Date: 2025/8/8
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 用户登录，返回token
---------------------------------------------------------------------
"""

from datetime import timedelta

from fastapi import APIRouter, Depends, Request
from fastapi.security import OAuth2PasswordRequestForm

from .service import authenticate_user, create_access_token

# dependencies
from app.api.v1.dependencies.common import get_current_user


# token相关配置
from app.core.config import ACCESS_TOKEN_EXPIRE_MINUTES

# schema
from .schemas import TokenOut, Token, UserOut, UserNo

# models

router = APIRouter(prefix="/security", tags=["安全"])


@router.post("/token", summary="获取访问令牌token", response_model=TokenOut)
async def login_for_access_token(
    request: Request, form_data: OAuth2PasswordRequestForm = Depends()
):
    """用户登录，返回token"""
    user = await authenticate_user(form_data.username, form_data.password)
    # 用户信息及登录账号保存到请求中
    request.state.current_user = user
    # 使用from表单提交情况
    request.state.form_data = {"user_no": form_data.username}
    access_token = await create_access_token(
        # 使用ORM再转字典, by_alias=True 使用别名
        data=dict(UserOut.model_validate(user).model_dump(by_alias=True)),
        expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES),
    )
    return TokenOut(
        code="0000",
        msg="OK",
        access_token=access_token,
        token_type="bearer",
        data=Token(
            access_token=access_token,
            token_type="bearer",
        ),
    )


@router.get("/user/me", summary="当前用户信息")
async def get_current_user(user=Depends(get_current_user)):
    return {"ok": "ok", "msg": user}
